package com.distributed.kv.dao.mapper;

import java.util.Optional;

import org.springframework.data.cassandra.repository.CassandraRepository;
import org.springframework.data.cassandra.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.distributed.kv.entity.IdSegment;

/**
 * ID段数据访问接口
 */
@Repository
public interface IdSegmentRepository extends CassandraRepository<IdSegment, String> {
    
    /**
     * 根据段标识查找
     */
    @Query("SELECT * FROM id_segments WHERE segment_key = :segmentKey")
    Optional<IdSegment> findBySegmentKey(@Param("segmentKey") String segmentKey);
    
    /**
     * 原子更新当前ID(使用轻量级事务LWT)
     */
    @Query("UPDATE id_segments SET current_id = :newCurrentId, max_id = :newMaxId, " +
           "updated_at = :updatedAt, version = :newVersion " +
           "WHERE segment_key = :segmentKey " +
           "IF version = :expectedVersion")
    boolean updateSegmentWithVersion(@Param("segmentKey") String segmentKey,
                                   @Param("newCurrentId") Long newCurrentId,
                                   @Param("newMaxId") Long newMaxId,
                                   @Param("updatedAt") java.time.Instant updatedAt,
                                   @Param("newVersion") Long newVersion,
                                   @Param("expectedVersion") Long expectedVersion);
}